package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;
import java.util.List;

/**
 * @author: 杨庆
 * @since: 2022.9.19 22:42
 * @description:
 */
@Service
public class ILoginServiceImpl implements ILoginService {
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserConverterMapper userConverterMapper;
    @Override
    public UserLoginResponse login(UserLoginRequest request) {
        //TODO 查询
        Example example = new Example(Member.class);
        example.createCriteria()
                .andEqualTo("username",request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(members)) {
            throw new BizException(UserRetCode.USERNAME_ALREADY_NOEXISTS.getCode(),UserRetCode.USERNAME_ALREADY_NOEXISTS.getMessage());
        }
        //TODO 用户存在，获取数据
        Member member = members.get(0);
        //TODO 判断用户的登录状态
        String isVerified = member.getIsVerified();
        if ("N".equals(isVerified)) {
            throw new ValidateException(UserRetCode.USER_ISVERFIED_ERROR .getCode(),UserRetCode.USER_ISVERFIED_ERROR.getMessage());
        }
        //TODO 判断密码 密码不对登录失败
        String autoPwd = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
        if (!autoPwd.equals(member.getPassword())) {
            throw new ValidateException(UserRetCode.USERORPASSWORD_ERRROR.getCode(),UserRetCode.USERORPASSWORD_ERRROR.getMessage());
        }
        //  生成一个token
        UserLoginResponse converter = userConverterMapper.converter(member);
        return converter;
    }
}
